﻿using HDSmartCommunity.BUS;
using HDSmartCommunity.DAL;
using HDSmartCommunity.DevicePlatform;
using HDSmartCommunity.Models;
using HDSmartCommunity.Serial;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace HDSmartCommunity.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PZTestController : ControllerBase
    {
        public PZDeviceSerialData pz_serial = SerialServer.pz_serial;
        /// <summary>
        ///查询Mqtt信息
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryMqtt")]
        public ResponseMessage QueryMqtt()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DeviceDAL deviceDAL = new DeviceDAL();
                PZMqttInfo list = deviceDAL.QueryPZMqttInfo();
                message.data = list;
                message.errcode = 0;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询Mqtt信息失败";
            }

            return message;
        }

        /// <summary>
        ///更新Mqtt信息
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateMqtt")]
        public ResponseMessage UpdateMqtt(PZMqttInfo pZMqttInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                DeviceDAL deviceDAL = new DeviceDAL();
                bool result = deviceDAL.UpdatePZMqttInfo(pZMqttInfo);
                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "更新失败";
                }

            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "更新异常";
            }

            return message;
        }

        /// <summary>
        ///查询基础信息
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryBasicInfo")]
        public ResponseMessage QueryBasicInfo()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                PZBasicInfo pZBasicInfo = new PZBasicInfo();
                pZBasicInfo.StorageStart = Convert.ToInt32(AppSettingsHelper.Configuration["StorageStart"]);
                pZBasicInfo.StorageCount = Convert.ToInt32(AppSettingsHelper.Configuration["StorageCount"]);
                pZBasicInfo.Liftid = Convert.ToInt32(AppSettingsHelper.Configuration["Liftid"]);
                pZBasicInfo.PZInterval = Convert.ToInt32(AppSettingsHelper.Configuration["PZInterval"]);
                pZBasicInfo.SerialNumber = AppSettingsHelper.Configuration["SerialNumber"];
                pZBasicInfo.Remark = AppSettingsHelper.Configuration["Remark"];
                message.data = pZBasicInfo;
                message.errcode = 0;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询基本信息失败";
            }

            return message;
        }

        /// <summary>
        ///更新基础信息
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateBasicInfo")]
        public ResponseMessage UpdateBasicInfo(PZBasicInfo pZBasicInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                string contentPath = AppDomain.CurrentDomain.BaseDirectory;   //项目根目录
                var filePath = contentPath + "appsettings.json";
                JObject jsonObject;
                using (StreamReader file = new StreamReader(filePath))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                    jsonObject["StorageStart"] = pZBasicInfo.StorageStart;
                    jsonObject["StorageCount"] = pZBasicInfo.StorageCount;
                    jsonObject["PZInterval"] = pZBasicInfo.PZInterval;
                    jsonObject["SerialNumber"] = pZBasicInfo.SerialNumber;
                    jsonObject["Liftid"] = pZBasicInfo.Liftid;
                    jsonObject["Remark"] = pZBasicInfo.Remark;
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
                {
                    jsonObject.WriteTo(jsonwriter);
                }
                DateTime startTime = DateTime.Now;
                while (true)
                {
                    TimeSpan secondSpan = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks);

                    if (secondSpan.TotalMilliseconds>1000)
                    {
                        break;
                    }
                }
               
                pz_serial.liftid = pZBasicInfo.Liftid;
                pz_serial.add_start = pZBasicInfo.StorageStart;
                pz_serial.add_count = pZBasicInfo.StorageCount;
                pz_serial.PZInterval = pZBasicInfo.PZInterval;
                pz_serial.numberno = pZBasicInfo.SerialNumber;
                pz_serial.remark = pZBasicInfo.Remark;

                message.errcode = 0;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "更新基础信息";
            }

            return message;
        }

        /// <summary>
        ///下载测试数据
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("PZDownLoadLog")]
        public ResponseMessage PZDownLoadLog(string StartTime, string EndTime, string NumberNo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                LogBUS logBUS = new LogBUS();
                message.data = logBUS.PZDownLoad(StartTime, EndTime, NumberNo);
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = "失败";
            }

            return message;
        }


        /// <summary>
        ///查询串口信息
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QuerySerialInfo")]
        public ResponseMessage QuerySerialInfo()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                SerialInfo serialInfo = new SerialInfo();
                serialInfo.BaudRate = AppSettingsHelper.Configuration["BaudRate"];
                serialInfo.Parity = Convert.ToInt32(AppSettingsHelper.Configuration["Parity"]);
                serialInfo.DataBits = Convert.ToInt32(AppSettingsHelper.Configuration["DataBits"]);
                serialInfo.StopBits = Convert.ToInt32(AppSettingsHelper.Configuration["StopBits"]);
                serialInfo.BaudRate_2 = Convert.ToInt32(AppSettingsHelper.Configuration["BaudRate_2"]);
                serialInfo.Parity_2 = Convert.ToInt32(AppSettingsHelper.Configuration["Parity_2"]);
                serialInfo.DataBits_2 = Convert.ToInt32(AppSettingsHelper.Configuration["DataBits_2"]);
                serialInfo.StopBits_2 = Convert.ToInt32(AppSettingsHelper.Configuration["StopBits_2"]);
                message.data = serialInfo;
                message.errcode = 0;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询串口信息失败";
            }

            return message;
        }
        /// <summary>
        ///更新基础信息
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateSerialInfo")]
        public ResponseMessage UpdateSerialInfo(SerialInfo serialInfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                string contentPath = AppDomain.CurrentDomain.BaseDirectory;   //项目根目录
                var filePath = contentPath + "appsettings.json";
                JObject jsonObject;
                using (StreamReader file = new StreamReader(filePath))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                    jsonObject["BaudRate"] = serialInfo.BaudRate;
                    jsonObject["Parity"] = serialInfo.Parity;
                    jsonObject["DataBits"] = serialInfo.DataBits;
                    jsonObject["StopBits"] = serialInfo.StopBits;
                    jsonObject["BaudRate_2"] = serialInfo.BaudRate_2;
                    jsonObject["Parity_2"] = serialInfo.Parity_2;
                    jsonObject["DataBits_2"] = serialInfo.DataBits_2;
                    jsonObject["StopBits_2"] = serialInfo.StopBits_2;
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
                {
                    jsonObject.WriteTo(jsonwriter);
                }
                message.errcode = 0;
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "更新基础信息";
            }

            return message;
        }
    }
}
